﻿using UnityEngine;
using System.Collections;

public class NetManager : MonoBehaviour {

    public string gameTypeName = "MyGameType";

    public void serverConnect()
    {
        Network.InitializeServer(32, 1024, !Network.HavePublicAddress());
        MasterServer.RegisterHost(gameTypeName, "game name", "comment");
        print("Server Builded!!");

        createHero();
    }

    public void clientConnect()
    {
        MasterServer.ClearHostList();
        MasterServer.RequestHostList(gameTypeName);
    }

    void Update()
    {
        string s;

        HostData[] data = MasterServer.PollHostList();
        if (data.Length != 0)
        {
            foreach (HostData e in data)
            {
                s = "遊戲類型：" + e.gameType + " 遊戲名稱：" + e.gameName
                + " , 內部IP : " + e.ip[0] + " : " + e.port;

                if (e.ip.Length > 2)
                {
                    s += " , 外部IP：" + e.ip[2] + " : " + e.port;
                }

                foreach (string h in e.ip)
                {
                    print("所有IP：" + h + ":" + e.port);
                }
                if (e.connectedPlayers < e.playerLimit)
                {
                    if (e.useNat)
                    {
                        print("使用NAT穿透");
                    }
                    else
                    {
                        print("直接連接到主機");
                    }
                    print(Network.Connect(e.ip, e.port));
                }
            }
            MasterServer.ClearHostList();
        }
    }

    void OnFailedToConnect(NetworkConnectionError error)
    {
        Debug.Log("客戶端：無法連接到伺服器: " + error);
    }

    void OnConnectedToServer()
    {
        Debug.Log("客戶端：已連接至伺服器");

        GameObject hero = createHero();
        //NetworkView netView = hero.GetComponent<NetworkView>();
        //netView.viewID = Network.AllocateViewID();
        //Network.
    }

    public GameObject heroPref;

    void OnPlayerConnected(NetworkPlayer player)
    {
    }

    void OnPlayerDisconnected(NetworkPlayer player)
    {
    }

    private GameObject createHero()
    {
        GameObject hero = Network.Instantiate(heroPref,Vector3.zero,Quaternion.identity,0) as GameObject;
        NetworkView netView = hero.GetComponent<NetworkView>();
        Debug.Log(netView.viewID);
        return hero;
    }

    //[RPC]
    //private void createOthersHero(NetworkViewID id)
    //{
    //    GameObject hero = createHero();
    //    NetworkView netView = hero.GetComponent<NetworkView>();
    //    netView.viewID = id;
    //}
}
